package com.macro.mall.common.util;

import java.math.BigDecimal;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

public class TencentMapUtils {

    private final static String DISTANCE_URL = "https://apis.map.qq.com/ws/distance/v1/matrix/?mode=walking&from=%s&to=%s&key=%s";

    public static BigDecimal getSingleDistance(String from, String to, String key) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> resData = restTemplate.getForEntity(String.format(DISTANCE_URL, from, to, key),
                JSONObject.class);
        BigDecimal distance = BigDecimal.ZERO;
        if (resData.getStatusCode() == HttpStatus.OK) {
            JSONObject data = resData.getBody();
            if (data.getInt("status") != 0) {
                throw new RuntimeException(data.getStr("message"));
            }
            JSONObject result = data.getJSONObject("result");
            if (result == null) {
                throw new RuntimeException("腾讯地图计算结果为空");
            }
            JSONArray rows = result.getJSONArray("rows");
            if (rows == null || rows.size() < 1) {
                throw new RuntimeException("腾讯地图结果数组（行）为空");
            }
            JSONArray elements = rows.getJSONObject(0).getJSONArray("elements");
            if (elements == null || elements.size() < 1) {
                throw new RuntimeException("腾讯地图结果数组（列）为空");
            }
            JSONObject entity = elements.getJSONObject(0);
            distance = entity.getBigDecimal("distance");
        }
        System.out.println("两点距离：" + distance + "米");
        return distance;
    }

}
